package com.whutosa.template.server.service.impl;

import com.whutosa.template.server.dao.PersonDao;
import com.whutosa.template.server.model.Person;
import com.whutosa.template.server.service.PersonService;
import com.yml666.jpa.utils.QueryUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Sort;
import org.springframework.stereotype.Service;

import javax.persistence.criteria.Predicate;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by 19110 on 2016/9/12.
 */
@Service
public class PersonServiceImpl implements PersonService {

    /**
     * 自定义排序
     */
    private static final Sort pidDesc = new Sort(Sort.Direction.DESC, "pid");
    private static final Sort pidAsc = new Sort(Sort.Direction.ASC, "pid");

    @Autowired
    private PersonDao personDao;

    @Override
    public Page<Person> getAllPeople(int page, int size) {
        return personDao.findAll(new PageRequest(page, size, pidDesc));
    }

    @Override
    public Page<Person> findByNameLike(String name, int page, int size) {
        return personDao.findByNameLike("%" + name + "%", new PageRequest(page, size));
    }

    @Override
    public Page<Person> query(Person condtion, int page, int size) {
        return personDao.findAll((root, query, cb) -> {

            List<Predicate> predicates = new ArrayList<>();

            //介入示例
            predicates.add(root.get("name").in("小明", "杨明亮"));

            return QueryUtil.toPredicate(root, query, cb, condtion, predicates);
        }, new PageRequest(page, size));
    }
}
